#!/bin/bash

# Go版本问题修复脚本

set -e

echo "🔧 Go版本问题修复脚本"
echo "================================"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "1. 检查当前Go版本..."
CURRENT_GO_VERSION=$(go version 2>/dev/null | awk '{print $3}' | sed 's/go//')
echo "当前Go版本: $CURRENT_GO_VERSION"

# 检查是否是问题版本
if [[ "$CURRENT_GO_VERSION" == "1.24"* ]]; then
    echo -e "${RED}⚠️  检测到Go 1.24版本，存在已知兼容性问题${NC}"
    NEED_DOWNGRADE=true
elif [[ "$CURRENT_GO_VERSION" > "1.22" ]]; then
    echo -e "${YELLOW}⚠️  检测到较新的Go版本，可能存在兼容性问题${NC}"
    NEED_DOWNGRADE=true
else
    echo -e "${GREEN}✅ Go版本看起来正常${NC}"
    NEED_DOWNGRADE=false
fi

echo -e "\n2. 清理Go模块缓存..."
go clean -modcache
echo -e "${GREEN}✅ 缓存已清理${NC}"

echo -e "\n3. 重新下载依赖..."
go mod download
echo -e "${GREEN}✅ 依赖已重新下载${NC}"

echo -e "\n4. 整理模块依赖..."
go mod tidy
echo -e "${GREEN}✅ 模块依赖已整理${NC}"

echo -e "\n5. 尝试编译项目..."
if go build -o spam3uk main.go; then
    echo -e "${GREEN}✅ 编译成功！${NC}"
    echo "可执行文件: ./spam3uk"
    
    echo -e "\n6. 测试运行..."
    if ./spam3uk --help 2>/dev/null || timeout 3 ./spam3uk 2>/dev/null; then
        echo -e "${GREEN}✅ 程序可以正常运行${NC}"
    else
        echo -e "${YELLOW}⚠️  程序运行可能需要配置文件${NC}"
    fi
else
    echo -e "${RED}❌ 编译失败${NC}"
    
    if [ "$NEED_DOWNGRADE" = true ]; then
        echo -e "\n${YELLOW}建议解决方案:${NC}"
        echo "1. 降级Go版本到1.21或1.22:"
        echo "   wget https://golang.org/dl/go1.21.12.linux-amd64.tar.gz"
        echo "   sudo rm -rf /usr/local/go"
        echo "   sudo tar -C /usr/local -xzf go1.21.12.linux-amd64.tar.gz"
        echo ""
        echo "2. 或者使用Docker运行:"
        echo "   docker run --rm -v \$(pwd):/app -w /app golang:1.21 go build -o spam3uk main.go"
        echo ""
        echo "3. 或者修改代码兼容新版本Go"
    fi
    
    exit 1
fi

echo -e "\n${GREEN}🎉 修复完成！${NC}"
echo "================================"
echo "✅ 现在可以使用以下方式运行:"
echo "   方式1: ./spam3uk"
echo "   方式2: go run main.go"
echo ""
echo "🔧 如果仍有问题，请运行:"
echo "   ./diagnose-go.sh"
